package com.sr.recitewords.controller;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sr.recitewords.common.vo.BaseData;
import com.sr.recitewords.common.vo.PageData;
import com.sr.recitewords.common.vo.RespData;
import com.sr.recitewords.common.vo.RespPage;
import com.sr.recitewords.exception.BizException;
import com.sr.recitewords.service.redis.RedisService;
import org.springframework.web.bind.annotation.CrossOrigin;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @date 2019/9/25 14:22
 */
public abstract class BaseController {

    @Resource
    private HttpServletRequest request;
    @Resource
    private HttpServletResponse response;
    @Resource
    private RedisService redisService;


    public HttpServletRequest getRequest() {
        return request;
    }

    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }

    public HttpServletResponse getResponse() {
        return response;
    }

    public void setResponse(HttpServletResponse response) {
        this.response = response;
    }

    protected static <E> RespPage<E> getPageRtnData(Page<E> page) {
        RespPage<E> respJson = new RespPage<>();
        respJson.setData(new PageData<E>((int) page.getTotal(), (int) page.getPages(), page.getRecords()));
        return respJson;
    }

    protected static <E> RespData<E> getRtnData(E e) {
        RespData<E> respJson = new RespData<>();
        respJson.setData(new BaseData<>(e));
        return respJson;
    }

    /**
     * 获得系统访问的前缀地址，如：http://www.xxx.com:8080/
     */
    protected String getBasePath() {
        String path = request.getContextPath();
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
    }

    //获取访问的http或https
    protected String isHttp() {
        return request.getScheme();
    }


    /**
     * 获取客户端真实ip
     *
     * @return
     */
    protected String getRemoteIP() {
//        String ip = request.getHeader("X-nginx-real-ip");
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    protected String getToken() {
        String token = request.getHeader("X-Access-Token");
        if (StringUtils.isEmpty(token)) {
            token = request.getParameter("X-Access-Token");
        }
        if (StringUtils.isBlank(token)) {
            throw new BizException("123", "UserErrorEnum.USER_NOT_Token");
        }
        return token;
    }
//    protected UserEntity getUserEntity(String userType) {
//        String token = getToken();
//        boolean expire = RedisUtil.hasKey(getToken());
//        if (!expire) {
//            throw new BizException(UserErrorEnum.USER_ExpireToken);
//        }
//        UserEntity userEntity = JSONObject.parseObject(RedisUtil.get(token), UserEntity.class);
//        if (userEntity == null) {
//            throw new BizException(UserErrorEnum.USER_NeedToken);
//        }
//        else {
//            //更新token
//            RedisUtil.expire(token, 3, TimeUnit.HOURS);
//            if (userType != null) {
//                if (!token.split("-")[1].trim().equals("" + userType)) {
//                    throw new BizException(UserErrorEnum.USER_UserType);
//                }
//            }
//        }
//        return userEntity;
//    }

    protected String getType() {
        String token = getToken();
        return token.split("-")[0].trim();
    }

    /**
     * 新增BY HEKAI  2021/3/19
     *
     * @return
     */
    protected String getUserId() {
        String token = getToken();
        boolean expire = redisService.hasKey(token);
        if (!expire) {
            throw new BizException("loginOut", "用户未登入");
        }
        Object o = redisService.getObjectFromSessionByKey(token, "userId");
        return o.toString();
    }

    protected String getUserName() {
        String token = getToken();
        boolean expire = redisService.hasKey(token);
        if (!expire) {
            throw new BizException("loginOut", "用户未登入");
        }
        Object o = redisService.getObjectFromSessionByKey(token, "userName");
        return o.toString();
    }


    protected String getDeptName() {
        String token = getToken();
        boolean expire = redisService.hasKey(token);
        if (!expire) {
            throw new BizException("loginOut", "用户未登入");
        }
        Object o = redisService.getObjectFromSessionByKey(token, "deptName");
        return ObjectUtils.isNotEmpty(o) ? o.toString() : "";
    }

    /**
     * 获取默认的返回体结构
     *
     * @param resultCode
     * @param errMsg
     * @return
     */
    protected RespData getDefaultRtnData(int resultCode, String errMsg) {
        RespData respData = new RespData();
        BaseData baseData = new BaseData();
        respData.setData(baseData);
        respData.getData().setResultCode(resultCode);
        respData.getData().setErrMsg(errMsg);
        return respData;
    }

    protected RespData getDefaultRtnData() {
        RespData respData = new RespData();
        BaseData baseData = new BaseData();
        respData.setData(baseData);
        respData.getData().setResultCode(200);
        respData.getData().setErrMsg("操作成功");
        return respData;
    }

}
